// This file contains everything specific to stacking units together
var CB;
(function (CB) {
    var Stacking;
    (function (Stacking) {
        var cb = global.craig_brett;
        function stackUnits(e) {
            /// <summary>Handles stacking units together</summary>
            var source = e.source;
            var target = e.target;
            if (!target)
                return; // if there's somehow no target... er... bummer
            var skill = e.skill;
            if (skill && e.success == false)
                return; // we only stack if the skill was successful
            var flags = skill.ScriptFlags;
            var stackIntoType = flags.get("stack_into");
            var stackNumber = flags.get("stack_number");
            if (!stackNumber) {
                say("No stack_number script flag has been set, so no stacking will occur");
                return;
            }
            var targetTile = target.Tile;
            var foundUnits = new Array();
            foundUnits.push(target);
            // iterate over the units on the targetTile and try to find the right amount of them
            var tileUnits = targetTile.Units;
            for (var index = 0; index < tileUnits.length; index++) {
                var unit = tileUnits[index];
                // we've already put the target in our collection
                if (unit.ID == target.ID)
                    continue;
                if (unit.IndexedType == target.IndexedType)
                    foundUnits.push(unit);
                // now check to seeif we have enough. if we do, stop!
                if (foundUnits.length == stackNumber)
                    break; // no need to keep on looking, we have our stack of units
            }
            if (foundUnits.length < stackNumber) {
                say("Not enough units of this type on this tile to use a stacking skill");
                return;
            }
            // borrowing some logic from change_unit_type here
            var stackUnit = shared.CreateUnit(stackIntoType);
            if (stackUnit == null) {
                say("Error: Unit type {0} not found.".format(stackIntoType));
                return;
            }
            CB.Utils.applyRelevantPointsFromOldUnitToNew(target, stackUnit);
            stackUnit.Team = target.Team;
            for (var index = 0; index < foundUnits.length; index++) {
                var unit = foundUnits[index];
                CB.Utils.moveWholeInventoryBetweenUnits(unit, stackUnit);
                shared.Map.RemoveUnit(unit);
            }
            shared.Map.AddUnit(stackUnit, targetTile.X, targetTile.Y);
            return stackUnit;
        }
        Stacking.stackUnits = stackUnits;
    })(Stacking = CB.Stacking || (CB.Stacking = {}));
})(CB || (CB = {}));
